package com.aos.erp.gov.ex.task.mq;

import com.aos.erp.common.utils.JsonUtils;
import com.aos.erp.gov.ex.enums.RegisterTaskType;
import com.aos.erp.gov.ex.model.GovExRegisterTask;
import com.aos.erp.gov.ex.model.dto.CheckResultFailDTO;
import com.aos.erp.gov.ex.model.dto.GovExNewStudentDTO;
import com.aos.erp.gov.ex.service.GovExRegisterTaskService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class StudentListenerReceiver {
    @Resource
    private GovExRegisterTaskService registerTaskService;

    @RabbitListener(queues = QueueConstants.toGovNewStudent, concurrency = "2-5")
    public void getNewStudentInfo(@Payload List<GovExNewStudentDTO> list, Channel channel, Message message) throws IOException {

        log.info("收到getNewStudentInfo消息：" + JsonUtils.toJSONString(list));

        for (GovExNewStudentDTO bean : list) {
            GovExRegisterTask task = new GovExRegisterTask();
            BeanUtils.copyProperties(bean, task);
            registerTaskService.addBean(task);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @RabbitListener(queues = QueueConstants.toGovStudentSubmitted)
    public void submittedInfo(@Payload List<String> idnumList, Channel channel, Message message) throws IOException {
        log.info("收到submittedInfo消息：" + JsonUtils.toJSONString(idnumList));
        registerTaskService.saveSubmitted(idnumList, RegisterTaskType.manual);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @RabbitListener(queues = QueueConstants.toGovStudentSuccess)
    public void successInfo(@Payload List<String> idnumList, Channel channel, Message message) throws IOException {

        log.info("收到successInfo消息：" + JsonUtils.toJSONString(idnumList));
        registerTaskService.saveConfirmSuccess(idnumList, RegisterTaskType.manual);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @RabbitListener(queues = QueueConstants.toGovStudentFailed)
    public void failedInfo(@Payload List<CheckResultFailDTO> failedList, Channel channel, Message message) throws IOException {
        log.info("收到failedInfo消息：" + JsonUtils.toJSONString(failedList));
        for (CheckResultFailDTO dto : failedList) {
            registerTaskService.saveConfirmFailed(dto, RegisterTaskType.manual, false);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}